package com.woniu.util;

import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;


/**
 * @author 李桢
 * @date 2021/4/2 14:04
 */

public class JwtVerifyGetUserNameUtils {


    /** 私钥密码，保存在服务器，客户端是不会直到密码的，以防止被攻击* */
    private static final String SECRET = "mysecret";


    /** 加密方式* */
    private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;


    /** 对私钥进行加密* */
    private static Key getkey() {
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        return new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    }


    /*** 解密Token查看其是否合法*/
    public static boolean verifyToken(String token) {

        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey(getkey()).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return body != null;
    }

    /**获取用户名**/
    public static String getUsername(String token) {
        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey(getkey()).parseClaimsJws(token).getBody();
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("超时", e);
        } catch (Exception e) {
            throw new RuntimeException("未知错误", e);
        }
        return (String) body.get("userName");
    }

}
